from fastapi import FastAPI, Request
from pydantic import BaseModel
from apis.ping import ping_router
from apis.user import users_router
from apis.login import logins_router
from apis.tushan_admin import tuashan_admin_router
from apis.datasource import ds_router
from components.log import init_log, log
from components.env import init_env
from components.db import close_db, init_db

from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import http

from utils.resp import BusinessException, resp_err, resp_json, resp_ok, resp_data


router_prefix = "/api"

app = FastAPI()
app.include_router(ping_router, prefix=router_prefix)
app.include_router(users_router, prefix=router_prefix)
app.include_router(logins_router, prefix=router_prefix)

app.include_router(tuashan_admin_router)
app.include_router(ds_router, prefix=router_prefix)


app.mount("/chat", StaticFiles(directory="static/chat_app"), name="chat")


@app.get("/chat", response_class=RedirectResponse)
async def redirect_fastapi():
    return "/chat/index.html"

@app.get("/", response_class=RedirectResponse)
async def redirect_fastapi():
    return "/chat/index.html"

origins = [
    # "http://localhost.tiangolo.com",
    # "https://localhost.tiangolo.com",
    # "http://localhost",
    'http://127.0.0.1:5174',
    "http://localhost:5174",
    "http://127.0.0.1:8068",
    "http://localhost:8068",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    # allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["X-Total-Count", "*"],
)


@app.exception_handler(BusinessException)
async def general_exception_handler(request: Request, e: BusinessException):
    return JSONResponse(
        # status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR,
        # content={"message": str(e)},
        status_code=http.HTTPStatus.OK,
        content=resp_json(e.code, e.message, None),
    )

# @app.exception_handler(AuthJWTException)
# def authjwt_exception_handler(request: Request, exc: AuthJWTException):
#     print("authjwt_exception_handler...")
#     return JSONResponse(
#         status_code=exc.status_code,
#         content=resp_err(exc.message)
#     )



# fix error: authjwt_secret_key must be set when using symmetric algorithm HS256
class Settings(BaseModel):
    authjwt_algorithm: str = "HS256"
    authjwt_secret_key: str = "my-dev-secret"
    authjwt_token_location: set = {"cookies"}
    authjwt_cookie_csrf_protect: bool = True
    authjwt_cookie_samesite: str = "none"
     # Only allow JWT cookies to be sent over https
    authjwt_cookie_secure: bool = False
    # Change to 'lax' in production to make your website more secure from CSRF Attacks, default is None
    authjwt_cookie_samesite: str = 'lax'


@AuthJWT.load_config
def get_config():
    return Settings()


@app.on_event("startup")
async def startup():
    init_log()
    init_env()
    await init_db()

    log.info("app start")


@app.on_event("shutdown")
async def shutdown():
    close_db()
    log.info("app shutdown")
